import { useEffect, useState } from 'react';
import { searchSong } from '@/services/global/base';
import { debounce } from 'lodash';

import { Select } from 'antd';
import { SongItem } from '@/services/global/type';

const { Option } = Select;

type Props = {
  value?: string;
  onChange?: (value: string, songItem?: SongItem) => void;
  [key: string]: any;
};

const SelectSong: React.FC<Props> = ({ value, onChange, ...rest }) => {
  const [data, setData] = useState<SongItem[]>([]);
  const { mode } = rest;

  const getSongItemList = async (searchValue: string) => {
    const res = await searchSong(searchValue);
    setData(res.data.list);
  };

  const debounceSearch = debounce(getSongItemList, 500);

  const handleSearch = (searchValue: string) => {
    if (searchValue === '') {
      setData([]);
      return;
    }

    debounceSearch(searchValue);
  };

  useEffect(() => {
    if (value && data.length === 0 && mode !== 'multiple' && mode !== 'tags') {
      handleSearch(value);
    }
  }, [value, data, mode]);

  const handleChange = (ret: string) => {
    if (onChange) {
      const songItem = data.find((item) => item.trackId === Number(ret));
      onChange(ret, songItem);
    }
  };

  const options = data.map((item) => (
    <Option key={item.trackId} value={String(item.trackId)}>
      <span>{`${item.trackId} - ${item.trackName}`}</span>
    </Option>
  ));

  return (
    <Select
      showSearch
      value={value}
      placeholder="输入歌曲ID歌曲名搜索"
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      {...rest}
    >
      {options}
    </Select>
  );
};

export default SelectSong;
